<template>
    <div class="relative transition-all duration-300 ease-in-out border-l border-gray-700"
        :class="collapsed ? 'w-12' : 'w-[300px]'">

        <!-- 折叠状态的历史面板 -->
        <div v-if="collapsed" class="w-12 h-full bg-[#1a1a1a] flex flex-col items-center py-4">
            <el-button size="small" class="!bg-transparent !border-gray-600 !text-gray-400 hover:!text-white mb-4"
                @click="toggleCollapse">
                <el-icon>
                    <ArrowLeft />
                </el-icon>
            </el-button>

            <!-- 并发轮询状态指示器（折叠时） -->
            <div v-if="activePollingCount > 0" class="mb-4">
                <div class="w-8 h-8 rounded-lg bg-blue-500/20 flex items-center justify-center"
                    :title="`${activePollingCount} 个任务正在处理中`">
                    <div class="w-3 h-3 border-2 border-blue-500 border-t-transparent rounded-full animate-spin">
                    </div>
                </div>
                <div class="text-xs text-gray-400 mt-1 text-center">
                    {{ activePollingCount }}
                </div>
            </div>

            <!-- 历史记录指示器 -->
            <div class="flex flex-col space-y-2">
                <div v-for="history in historyList.slice(0, 3)" :key="history.id"
                    class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-500 rounded-lg flex items-center justify-center cursor-pointer hover:scale-110 transition-transform"
                    :title="history.name" @click="loadHistoryModel(history)">
                    <el-icon class="text-white text-xs">
                        <Box />
                    </el-icon>
                </div>
                <div v-if="historyList.length > 3"
                    class="w-8 h-8 bg-gray-600 rounded-lg flex items-center justify-center cursor-pointer hover:scale-110 transition-transform"
                    :title="`还有${historyList.length - 3}个模型`" @click="toggleCollapse">
                    <span class="text-xs text-gray-300">+{{ historyList.length - 3 }}</span>
                </div>
            </div>
        </div>

        <!-- 展开状态的历史面板 -->
        <div v-else class="w-[300px] bg-[#1a1a1a] h-full flex flex-col">
            <!-- 头部 -->
            <div class="p-6 pb-4 border-b border-gray-700">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-white font-medium text-lg">生成历史</h3>
                    <div class="flex items-center space-x-2">
                        <el-button size="small" text class="!text-blue-500" @click="handleRefreshHistory"
                            :loading="historyState.loading">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                        </el-button>
                        <!-- 折叠按钮 -->
                        <el-button size="small"
                            class="!bg-transparent !border-gray-600 !text-gray-400 hover:!text-white"
                            @click="toggleCollapse">
                            <el-icon>
                                <ArrowRight />
                            </el-icon>
                        </el-button>
                    </div>
                </div>

                <!-- 并发轮询状态显示（展开时） -->
                <div v-if="activePollingCount > 0" class="mb-4 p-4 bg-gray-800/50 rounded-lg border border-blue-500/30">
                    <div class="flex items-center space-x-2 mb-3">
                        <div class="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin">
                        </div>
                        <span class="text-white font-medium text-sm">正在处理 {{ activePollingCount }} 个任务</span>
                    </div>

                    <div class="text-xs text-gray-400">
                        <div v-for="(pollInfo, taskId) in activePollingTasks" :key="taskId"
                            class="flex justify-between items-center mb-1">
                            <span>任务 {{ taskId.slice(-8) }}</span>
                            <span>{{ pollInfo.attempts }}/{{ pollingState.pollingConfig.maxAttempts }} 次</span>
                        </div>
                    </div>

                    <!-- 手动操作按钮 -->
                    <div class="flex items-center space-x-2 mt-3">
                        <el-button size="small" text class="!text-red-400" @click="handleStopAllPolling">
                            停止全部轮询
                        </el-button>
                        <el-button size="small" text class="!text-blue-400" @click="handleRestartPolling">
                            重启轮询
                        </el-button>
                    </div>
                </div>

                <!-- 生成进度显示（展开时） -->
                <div v-if="generatorState.isGenerating"
                    class="mb-4 p-4 bg-gray-800/50 rounded-lg border border-orange-500/30">
                    <div class="flex items-center space-x-2 mb-3">
                        <div class="w-4 h-4 border-2 border-orange-500 border-t-transparent rounded-full animate-spin">
                        </div>
                        <span class="text-white font-medium text-sm">正在生成中...</span>
                    </div>

                    <div class="flex items-center justify-between text-sm text-gray-300 mb-2">
                        <span>{{ generatorState.statusText }}</span>
                        <span class="font-medium text-orange-400">{{ generatorState.progress }}%</span>
                    </div>

                    <el-progress :percentage="generatorState.progress" :show-text="false" :stroke-width="6" :color="{
                        '0%': '#f97316',
                        '50%': '#fb923c',
                        '100%': '#22c55e'
                    }" class="mb-2" />

                    <div class="text-xs text-gray-500 flex items-center justify-between">
                        <span>{{ generatorState.currentStep }}</span>
                        <span v-if="generatorState.estimatedTime > 0">
                            预计: {{ generatorState.estimatedTime }}秒
                        </span>
                    </div>
                </div>

                <!-- 筛选和排序 -->
                <div class="flex items-center space-x-3">
                    <el-select v-model="filterState.type" size="small" class="flex-1" placeholder="筛选类型"
                        @change="handleFilterChange">
                        <el-option label="全部" value="all" />
                        <el-option label="文生3D" value="text" />
                        <el-option label="图生3D" value="image" />
                    </el-select>
                    <el-select v-model="filterState.sortBy" size="small" class="flex-1" placeholder="排序"
                        @change="handleSortChange">
                        <el-option label="最新" value="time_desc" />
                        <el-option label="最旧" value="time_asc" />
                        <el-option label="名称" value="name" />
                    </el-select>
                </div>
            </div>

            <!-- 历史记录列表 -->
            <div class="flex-1 overflow-y-auto p-6 pt-4" @scroll="handleScroll">
                <!-- 加载状态 -->
                <div v-if="historyState.loading && historyList.length === 0" class="text-center text-gray-500 py-12">
                    <div
                        class="w-8 h-8 border-2 border-gray-500 border-t-transparent rounded-full animate-spin mx-auto mb-4">
                    </div>
                    <div class="text-sm">正在加载历史记录...</div>
                </div>

                <!-- 历史记录列表 -->
                <div v-else-if="filteredHistory.length" class="space-y-3">
                    <div v-for="history in filteredHistory" :key="history.id"
                        class="bg-gray-800 rounded-lg p-4 cursor-pointer hover:bg-gray-700 transition-all duration-200 group relative"
                        @click="loadHistoryModel(history)">

                        <!-- 模型预览图 -->
                        <div class="flex items-center space-x-3 mb-3">
                            <div
                                class="w-14 h-14 rounded-lg overflow-hidden bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center relative">
                                <img v-if="history.thumbnail" :src="history.thumbnail" :alt="history.name"
                                    class="w-full h-full object-cover" />
                                <el-icon v-else class="text-white text-xl">
                                    <Box />
                                </el-icon>

                                <!-- 状态指示器 -->
                                <div v-if="history.status !== 'completed'"
                                    :class="`absolute top-1 right-1 w-2 h-2 rounded-full ${getStatusColor(history.status)}`">
                                </div>

                                <!-- 轮询状态指示器 -->
                                <div v-if="history.status === 'processing' && isTaskBeingPolled(history.originalData?.taskId)"
                                    class="absolute inset-0 bg-blue-500/20 flex items-center justify-center">
                                    <div
                                        class="w-3 h-3 border-2 border-blue-400 border-t-transparent rounded-full animate-spin">
                                    </div>
                                </div>
                            </div>

                            <div class="flex-1 min-w-0">
                                <div class="text-white text-sm font-medium truncate mb-1">{{ history.name }}</div>
                                <div class="flex items-center space-x-2 text-xs text-gray-400">
                                    <span>{{ history.createTime }}</span>
                                    <span>•</span>
                                    <span :class="getTypeColor(history.type)">{{ getTypeLabel(history.type) }}</span>
                                </div>
                                <div class="text-xs text-gray-500 mt-1">{{ history.faces }} 面</div>
                            </div>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="flex items-center justify-between">
                            <div class="flex items-center space-x-2">
                                <el-tag :type="getStatusTagType(history.status)" size="small">
                                    {{ getStatusLabel(history.status) }}
                                </el-tag>
                                <el-tag v-if="history.isStarred" type="warning" size="small">
                                    <el-icon>
                                        <Star />
                                    </el-icon>
                                </el-tag>
                                <!-- 轮询状态标签 -->
                                <el-tag
                                    v-if="history.status === 'processing' && isTaskBeingPolled(history.originalData?.taskId)"
                                    type="info" size="small">
                                    轮询中
                                </el-tag>
                            </div>

                            <div
                                class="flex items-center space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                <!-- 单独操作处理中的任务 -->
                                <el-button v-if="history.status === 'processing' && history.originalData?.taskId"
                                    size="small" text @click.stop="handleSingleTaskControl(history)">
                                    <el-icon
                                        :class="isTaskBeingPolled(history.originalData.taskId) ? 'text-red-400' : 'text-blue-400'">
                                        <component
                                            :is="isTaskBeingPolled(history.originalData.taskId) ? 'VideoPause' : 'VideoPlay'" />
                                    </el-icon>
                                </el-button>

                                <el-button size="small" text @click.stop="starHistory(history)">
                                    <el-icon :class="history.isStarred ? 'text-yellow-400' : 'text-gray-400'">
                                        <Star />
                                    </el-icon>
                                </el-button>
                                <el-button size="small" text @click.stop="downloadHistory(history)"
                                    :disabled="!history.downloadUrl">
                                    <el-icon class="text-green-400">
                                        <Download />
                                    </el-icon>
                                </el-button>
                                <el-button size="small" text @click.stop="deleteHistory(history)">
                                    <el-icon class="text-red-400">
                                        <Delete />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </div>

                    <!-- 加载更多指示器 -->
                    <div v-if="historyState.hasMore" class="text-center py-4">
                        <div v-if="historyState.loading"
                            class="flex items-center justify-center space-x-2 text-gray-500">
                            <div
                                class="w-4 h-4 border-2 border-gray-500 border-t-transparent rounded-full animate-spin">
                            </div>
                            <span class="text-sm">加载更多...</span>
                        </div>
                        <el-button v-else size="small" text class="!text-blue-500" @click="loadMoreHistory">
                            加载更多历史记录
                        </el-button>
                    </div>
                </div>

                <!-- 空状态 -->
                <div v-else-if="!historyState.loading" class="text-center text-gray-500 py-12">
                    <svg t="1758528289013" class="icon mx-auto mb-4 opacity-50" viewBox="0 0 1024 1024" width="64"
                        height="64" fill="currentColor">
                        <path
                            d="M349.141333 128a128 128 0 0 1 93.013334 40.106667l75.434666 79.786666a128 128 0 0 0 93.013334 40.106667H810.666667a128 128 0 0 1 128 128V768a128 128 0 0 1-128 128H213.333333a128 128 0 0 1-128-128V256a128 128 0 0 1 128-128h135.808zM213.333333 192a64 64 0 0 0-64 64v512a64 64 0 0 0 64 64h597.333334a64 64 0 0 0-64-64h-200.042667a192 192 0 0 1-139.562667-60.16l-75.413333-79.786667a64 64 0 0 0-46.506667-20.053333H213.333333z">
                        </path>
                    </svg>
                    <div class="text-sm mb-2">
                        {{ filterState.type === 'all' ? '暂无生成记录' : `暂无${getTypeLabel(filterState.type)}记录` }}
                    </div>
                    <div class="text-xs text-gray-600">
                        开始创建您的第一个3D模型吧！
                    </div>
                </div>

                <!-- 错误状态 -->
                <div v-if="historyState.error && !historyState.loading" class="text-center text-red-500 py-8">
                    <div class="text-sm mb-2">加载失败</div>
                    <div class="text-xs mb-4">{{ historyState.error }}</div>
                    <el-button size="small" @click="handleRefreshHistory">重试</el-button>
                </div>
            </div>

            <!-- 底部统计信息 -->
            <div v-if="historyList.length || statusStats.total > 0"
                class="p-6 pt-4 border-t border-gray-700 text-xs text-gray-500">
                <div class="flex items-center justify-between">
                    <span>共 {{ historyState.total }} 个模型</span>
                    <span>已加载: {{ historyList.length }}</span>
                </div>

                <!-- 状态统计 -->
                <div v-if="statusStats.total > 0" class="mt-2 pt-2 border-t border-gray-600">
                    <div class="flex items-center justify-between">
                        <span>状态统计</span>
                        <span class="text-green-400">{{ statusStats.completed }} 完成</span>
                    </div>
                    <div v-if="statusStats.processing > 0" class="flex items-center justify-between mt-1">
                        <span></span>
                        <span class="text-blue-400">{{ statusStats.processing }} 处理中</span>
                    </div>
                    <div v-if="statusStats.failed > 0" class="flex items-center justify-between mt-1">
                        <span></span>
                        <span class="text-red-400">{{ statusStats.failed }} 失败</span>
                    </div>
                </div>

                <!-- 并发轮询统计 -->
                <div v-if="activePollingCount > 0"
                    class="flex items-center justify-between mt-2 pt-2 border-t border-gray-600">
                    <span>活跃轮询</span>
                    <span class="font-medium text-blue-400">{{ activePollingCount }} 个任务</span>
                </div>

                <!-- 剩余生成次数显示 -->
                <div v-if="generatorState.remainingGenerations !== undefined"
                    class="flex items-center justify-between mt-2 pt-2 border-t border-gray-600">
                    <span>剩余生成次数</span>
                    <span class="font-medium"
                        :class="generatorState.remainingGenerations > 5 ? 'text-green-400' : 'text-orange-400'">
                        {{ generatorState.remainingGenerations }}
                    </span>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted } from 'vue'
import {
    Box, Refresh, ArrowLeft, ArrowRight, Star, Download, Delete, VideoPlay, VideoPause
} from '@element-plus/icons-vue'
import { useGenerator } from '@/hook/useGenerator'
import { useModelHistory } from '@/hook/useModelHistory'
import { ElMessage, ElMessageBox } from 'element-plus'

// ========== Props ==========
const props = defineProps({
    collapsed: {
        type: Boolean,
        default: false
    }
})

// ========== Emits ==========
const emit = defineEmits(['update:collapsed'])

// ========== 使用Hooks ==========
const {
    loadHistoryModel,
    generatorState
} = useGenerator()

const {
    // 历史记录相关
    historyList,
    historyState,
    filterState,
    filteredHistory,
    totalSize,
    statusStats,
    typeStats,
    refreshHistory,
    loadMoreHistory,
    initializeHistory,
    deleteHistoryRecord,
    updateStarStatus,

    // 新增：并发轮询相关
    pollingState,
    activePollingCount,
    startConcurrentPolling,
    resumeProcessingTasks,
    stopTaskPolling,
    stopAllPolling,

    // 工具方法
    formatFileSize,
    getStatusTagType,
    getStatusLabel,
    getTypeLabel,
    getStatusColor,
    getTypeColor,

    // 清理方法
    cleanup
} = useModelHistory()

// ========== 计算属性 ==========

// 活跃轮询任务信息
const activePollingTasks = computed(() => {
    const result = {}
    pollingState.activePolls.forEach((pollInfo, taskId) => {
        if (pollInfo.isActive) {
            result[taskId] = pollInfo
        }
    })
    return result
})

// ========== 生命周期 ==========
onMounted(async () => {
    console.log('[HistoryPanel] 组件挂载，初始化历史记录和并发轮询')

    // 初始化历史记录（会自动启动处理中任务的轮询）
    await initializeHistory()
})

onUnmounted(() => {
    console.log('[HistoryPanel] 组件卸载，清理资源')
    cleanup()
})

// ========== 方法 ==========

/**
 * 切换折叠状态
 */
const toggleCollapse = () => {
    emit('update:collapsed', !props.collapsed)
}

/**
 * 刷新历史记录
 */
const handleRefreshHistory = async () => {
    await refreshHistory()
}

/**
 * 处理筛选变化
 */
const handleFilterChange = () => {
    console.log('[HistoryPanel] 筛选条件变化:', filterState.type)
}

/**
 * 处理排序变化
 */
const handleSortChange = () => {
    console.log('[HistoryPanel] 排序方式变化:', filterState.sortBy)
}

/**
 * 滚动事件处理，实现滚动到底部自动加载更多
 */
const handleScroll = async (event) => {
    const { target } = event
    const { scrollTop, scrollHeight, clientHeight } = target

    if (scrollHeight - scrollTop - clientHeight < 100 && historyState.hasMore && !historyState.loading) {
        console.log('[HistoryPanel] 滚动到底部，自动加载更多')
        await loadMoreHistory()
    }
}

/**
 * 检查任务是否正在被轮询
 * @param {string} taskId - 任务ID
 * @returns {boolean} 是否正在轮询
 */
const isTaskBeingPolled = (taskId) => {
    if (!taskId) return false
    const pollInfo = pollingState.activePolls.get(taskId)
    return pollInfo && pollInfo.isActive
}

/**
 * 处理单个任务的轮询控制
 * @param {Object} history - 历史记录项
 */
const handleSingleTaskControl = async (history) => {
    const taskId = history.originalData?.taskId
    if (!taskId) return

    if (isTaskBeingPolled(taskId)) {
        // 停止轮询
        stopTaskPolling(taskId)
        ElMessage.info(`已停止轮询任务: ${taskId}`)
    } else {
        // 启动轮询
        await startConcurrentPolling([history])
        ElMessage.success(`已启动轮询任务: ${taskId}`)
    }
}

/**
 * 停止所有轮询
 */
const handleStopAllPolling = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要停止所有 ${activePollingCount.value} 个轮询任务吗？`,
            '停止轮询确认',
            {
                confirmButtonText: '确定停止',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        stopAllPolling()
        ElMessage.success('已停止所有轮询任务')
    } catch (error) {
        if (error === 'cancel') return
        console.error('停止轮询失败:', error)
    }
}

/**
 * 重启轮询
 */
const handleRestartPolling = async () => {
    console.log('[HistoryPanel] 重启处理中任务的轮询')
    await resumeProcessingTasks()

    if (activePollingCount.value > 0) {
        ElMessage.success(`已重启 ${activePollingCount.value} 个任务的轮询`)
    } else {
        ElMessage.info('没有需要轮询的处理中任务')
    }
}

/**
 * 收藏/取消收藏历史记录
 */
const starHistory = async (history) => {
    const newStarred = !history.isStarred
    const result = await updateStarStatus(history.id, newStarred)

    if (result.success) {
        history.isStarred = newStarred
    }
}

/**
 * 下载历史记录
 */
const downloadHistory = async (history) => {
    try {
        console.log('下载历史记录:', history.id)

        if (!history.downloadUrl) {
            ElMessage.warning('下载链接不可用')
            return
        }

        const link = document.createElement('a')
        link.href = history.downloadUrl
        link.download = `${history.name}.${history.format || 'glb'}`
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        ElMessage.success('开始下载模型文件')
    } catch (error) {
        console.error('下载模型失败:', error)
        ElMessage.error('下载失败，请重试')
    }
}

/**
 * 删除历史记录
 */
const deleteHistory = async (history) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除模型「${history.name}」吗？此操作不可恢复。`,
            '删除确认',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                confirmButtonClass: 'el-button--danger'
            }
        )

        console.log('删除历史记录:', history.id)

        // 如果正在轮询，先停止轮询
        const taskId = history.originalData?.taskId
        if (taskId && isTaskBeingPolled(taskId)) {
            stopTaskPolling(taskId)
        }

        const result = await deleteHistoryRecord(history.id)

        if (!result.success) {
            throw new Error(result.error)
        }
    } catch (error) {
        if (error === 'cancel') return
        console.error('删除模型失败:', error)
        ElMessage.error('删除失败，请重试')
    }
}
</script>

<style scoped>
/* 自定义滚动条样式 */
.overflow-y-auto::-webkit-scrollbar {
    width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
    background: #374151;
    border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
    background: #6b7280;
    border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
    background: #9ca3af;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-select) {
    width: 100% !important;
}

:deep(.el-select__wrapper) {
    background: #374151 !important;
    border: 1px solid #4b5563 !important;
    box-shadow: none !important;
    border-radius: 6px !important;
    transition: all 0.3s ease !important;
}

:deep(.el-select .el-select__wrapper:hover) {
    border-color: #6b7280 !important;
}

:deep(.el-select .el-select__wrapper.is-focus) {
    border-color: #3b82f6 !important;
    box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1) !important;
}

:deep(.el-select .el-input__inner) {
    color: #ffffff !important;
    background: transparent !important;
}

:deep(.el-select .el-input__suffix) {
    color: #9ca3af !important;
}

:deep(.el-select__popper.el-popper) {
    background: #2d2d2d !important;
    border: 1px solid #4b5563 !important;
    border-radius: 8px !important;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-select-dropdown__item) {
    color: #e5e7eb !important;
    background: transparent !important;
    transition: all 0.2s ease !important;
}

:deep(.el-select-dropdown__item:hover) {
    background: #374151 !important;
    color: #ffffff !important;
}

:deep(.el-select-dropdown__item.selected) {
    background: #3b82f6 !important;
    color: #ffffff !important;
}

/* 自定义消息框样式 */
:deep(.dark-message-box) {
    background: #1f2937 !important;
    border: 1px solid #4b5563 !important;
}

:deep(.dark-message-box .el-message-box__header) {
    background: #1f2937 !important;
    border-bottom: 1px solid #4b5563 !important;
}

:deep(.dark-message-box .el-message-box__title) {
    color: #ffffff !important;
}

:deep(.dark-message-box .el-message-box__content) {
    color: #e5e7eb !important;
}

:deep(.dark-message-box .el-message-box__btns) {
    border-top: 1px solid #4b5563 !important;
}

/* 自定义进度条样式 */
:deep(.el-progress-bar__outer) {
    background: #374151 !important;
    border-radius: 3px !important;
    height: 6px !important;
}

:deep(.el-progress-bar__inner) {
    border-radius: 3px !important;
}
</style>